package org.wlw.teacher.service.impl;

import org.wlw.teacher.anno.Resource;
import org.wlw.teacher.context.SystemContext;
import org.wlw.teacher.dao.IDepDao;
import org.wlw.teacher.dao.ITeacherDao;
import org.wlw.teacher.models.Department;
import org.wlw.teacher.models.Pager;
import org.wlw.teacher.models.Teacher;
import org.wlw.teacher.models.WebException;
import org.wlw.teacher.service.ITeacherService;
import org.wlw.teacher.utils.WebUtils;

import java.util.List;

public class TeacherService extends BaseService implements ITeacherService {
    private ITeacherDao teacherDao;
    private IDepDao depDao;

    @Resource
    public void setDepDao(IDepDao depDao) {
        this.depDao = depDao;
    }

    @Resource
    public void setTeacherDao(ITeacherDao teacherDao) {
        this.teacherDao = teacherDao;
    }

    @Override
    public void add(Teacher teacher) {
        if(teacher.getTno()==null||"".equals(teacher.getTno())) {
            throw new WebException("教师编号不能为空");
        }
        Teacher tt = new Teacher();
        tt.setTno(teacher.getTno());
        List<Teacher> teachers = this.list(tt);
        if(teachers.size()>0) {
            throw new WebException("添加的教师已经存在!不能添加");
        }
        Department dep = depDao.load(teacher.getDepId());
        if(dep==null) {
            throw new WebException("添加的教师部门不正确!不能添加!");
        }
        teacherDao.add(teacher);
    }

    @Override
    public void update(Teacher teacher) {
        Department dep = depDao.load(teacher.getDepId());
        if(dep==null) {
            throw new WebException("更新的教师部门不正确!不能更新!");
        }
        teacherDao.update(teacher);
    }

    @Override
    public void delete(int id) {
        teacherDao.delete(id);
    }

    @Override
    public Teacher load(int id) {
        return teacherDao.load(id);
    }

    @Override
    public Pager<Teacher> find(Teacher teacher) {
        if(teacher==null) teacher = new Teacher();
        WebUtils.setPagerObject(teacher);
        int totals = teacherDao.findByCount(teacher);
        List<Teacher> teachers = teacherDao.find(teacher);
        Pager<Teacher> pager = new Pager<>();
        pager.setData(teachers);
        WebUtils.setPager(pager,totals);
        return pager;
    }

    @Override
    public List<Teacher> list(Teacher teacher) {
        return teacherDao.list(teacher);
    }
}
